package com.archermind.boc.dal.business.service;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.archermind.boc.Logger;
import com.archermind.boc.dal.business.support.UserServiceSupport;
import com.archermind.boc.dal.mode.HibernateSessionFactory;
import com.archermind.boc.domain.User;

public class UserService {
	private Logger log = Logger.getLogger(UserService.class.getName());

	public boolean userAdded(User user) {
		boolean state = true;
		Transaction tx = null;
		Session session = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.save(user);
			tx.commit();
		} catch (HibernateException e) {
			state = false;
			tx.rollback();
			log.error("err: save is fail !", e);
		} finally {
			HibernateSessionFactory.closeSession(session);
		}
		return state;
	}

	public User getUser(String loginName, String passWord) {
		Session session = null;
		User user = null;
		try {
			session = HibernateSessionFactory.getSession();
			user = (User) session.createQuery(
					UserServiceSupport.HQL_VALIDATEUSER)
					.setString(0, loginName).setString(1, passWord)
					.setMaxResults(1).uniqueResult();
		} catch (HibernateException e) {
			log.error("err : Query is fail!", e);
			System.out.println("数据库连接发生异常!");
		} finally {
			HibernateSessionFactory.closeSession(session);
		}
		return user;
	}
	
	public boolean IsExistByLogName(String logName){
		boolean isExist = false;
		List<User> list = findAll();
		for(User u : list){
			String regName = u.getLoginName();
			if(logName.equals(regName)){
				isExist = true;
			}
		}
		return isExist;
	}
	
	public User findUserByByLogName(String loginName){
		List<User> list = findAll();
		for(User u :list){
			if(loginName.equals(u.getLoginName())){
				return u;
			}
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	private List<User> findAll(){
		Session session = null;
		List<User> list = null;
		try {
			session = HibernateSessionFactory.getSession();
			list= (List<User>) session.createQuery(UserServiceSupport.FIND_ALL).list();
		} catch (HibernateException e) {
			log.error("err : Query is fail!", e);
		} finally {
			HibernateSessionFactory.closeSession(session);
		}
		return list;
	}

	public User getUserById(int id) {
		Session session = null;
		User user = null;
		try {
			session = HibernateSessionFactory.getSession();
			user = (User) session.get(User.class, id);
		} catch (HibernateException e) {
			log.error("err : Query is fail!", e);
		} finally {
			HibernateSessionFactory.closeSession(session);
		}
		return user;
	}
}
